<%--
  Created by IntelliJ IDEA.
  User: User
  Date: 2020/10/24
  Time: 16:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>图书管理</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/layui/css/layui.css" charset="GBK">
    <script src="${pageContext.request.contextPath}/static/jquery-3.5.1.min.js" charset="GBK"></script>
    <script src="${pageContext.request.contextPath}/static/layui/layui.js"></script>
    <link href="${pageContext.request.contextPath}/static/toastr-master/toastr.min.css" rel="stylesheet"/>
    <script src="${pageContext.request.contextPath}/static/toastr-master/toastr.min.js" charset="GBK"></script>
</head>
<style>
    #left {
        width: 20%;
        float: left;
    }

    #right {
        width: 80%;
        float: right;
    }
</style>
<body>
<div id="left">
    <div class="layui-card">
        <div class="layui-card-header"></div>
        <div class="layui-card-body">
            <form class="layui-form" id="searchForm">
                <div class="layui-form-item">
                    <label class="layui-form-label">类型</label>
                    <div class="layui-input-inline">
                        <select name="typeid" id="typeid">
                            <option value="">请选择类型</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">书名</label>
                    <div class="layui-input-inline">
                        <input type="text" name="bookname" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">作者</label>
                    <div class="layui-input-inline">
                        <input type="text" name="author" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <button type="button" class="layui-btn" lay-submit lay-filter="searchBtn">搜索</button>
                    <button type="reset" id="searchReset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div id="right">
    <!--数据表格-->
    <table class="layui-hide " id="bookTable" lay-filter="bookTable"></table>

    <!--添加按钮组-->
    <div class="layui-hide" id="userToolbar">
        <button type="button" class="layui-btn layui-btn-radius layui-btn-sm layui-icon layui-icon-addition"
                lay-event="addBook">新增图书
        </button>
        <button type="button"
                class="layui-btn layui-btn-normal layui-btn-radius layui-btn-sm layui-icon layui-icon-refresh layui-anim layui-anim-scaleSpring"
                lay-event="refresh"></button>
    </div>

    <!--数据表格右侧按钮组-->
    <script type="text/html" id="userBar">
        {{#  if(d.status == 1){ }}
        <div class="layui-btn-group">
            <button class="layui-btn layui-btn-normal layui-btn-sm" lay-event="modify">修改</button>
            <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="delete">下架</button>
        </div>
        {{#  } else { }}
        <div class="layui-btn-group">
            <button class="layui-btn layui-btn-normal layui-btn-sm layui-btn-disabled">修改</button>
            <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="delete">上架</button>
        </div>
        {{#  } }}
    </script>

    <%--添加、修改图示的弹出层--%>
    <div id="addBookDiv" style="display: none">
        <form class="layui-form" id="addForm" lay-filter="addForm">
            <input name="bookid" style="display: none">
            <br>
            <div class="layui-form-item">
                <label class="layui-form-label">类型</label>
                <div class="layui-input-inline">
                    <select name="typeid" id="addtypeid" lay-verify="required">
                        <option value="">请选择类型</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">书名</label>
                <div class="layui-input-inline">
                    <input type="text" name="bookname" class="layui-input" lay-verify="required">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">作者</label>
                <div class="layui-input-inline">
                    <input type="text" name="author" class="layui-input" lay-verify="required">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">出版社</label>
                <div class="layui-input-inline">
                    <input type="text" name="publisher" class="layui-input" lay-verify="required">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">价格</label>
                <div class="layui-input-inline">
                    <input type="text" name="price" class="layui-input" lay-verify="required|price">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-inline">
                    <textarea type="text" name="remark" class="layui-input"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="button" class="layui-btn" lay-submit lay-filter="addBtn">确认</button>
                </div>
            </div>
        </form>
    </div>
</div>
</body>
<script>
    layui.use('table', function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;

        //书的类型下拉框填充
        $.ajax({
            url: 'typeServlet/getAllType',
            type: 'post',
            async: false,
            dataType: 'json',
            success: function (result) {
                let type = result;
                let option = "";
                for (let i = 0; i < type.length; i++) {
                    option += "<option value='" + type[i]['typeid'] + "'>" + type[i]['typename'] + "</option>";
                }
                $("#typeid").append(option);
                $("#addtypeid").append(option);
                form.render('select');
            }
        })

        //查询的提交事件
        form.on('submit(searchBtn)', function (data) {
            //layer.msg(JSON.stringify(data.field));
            //刷新一下table
            table.reload('bookTable', {
                where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                    typeid: data.field.typeid,
                    bookname: data.field.bookname,
                    author: data.field.author,
                },
                page: {
                    curr: 1
                }
            });

            return false;
        });

        //重置时要刷新表格
        $("#searchReset").click(function () {
            showTable()
        });

        //渲染职位表格-showTable()
        function showTable() {
            table.render({
                elem: '#bookTable'
                , url: '/bookServlet/getAllBook'//数据接口
                , toolbar: '#userToolbar'
                , even: true //开启隔行背景
                , page: true //开启分页
                , text: {
                    none: '暂无相关数据'
                }
                , cols: [[ //表头
                    {field: 'bookid', title: 'ID', align: 'center', hide: true}
                    , {field: 'bookname', title: '书名', align: 'center', width: 150}
                    , {field: 'typename', title: '类型', align: 'center', width: 100}
                    , {field: 'author', title: '作者', align: 'center'}
                    , {field: 'count', title: '库存', align: 'center', width: 80}
                    , {field: 'typeid', title: '类型Id', align: 'center', hide: true}
                    , {field: 'publisher', title: '出版社', align: 'center'}
                    , {
                        field: 'status', title: '状态', align: 'center', width: 70, templet: function (d) {
                            if (d.status == 1) return '<button class="layui-btn layui-btn-xs layui-btn-radius layui-btn-normal">上架</button>';
                            else return '<button class="layui-btn layui-btn-xs layui-btn-radius layui-btn-danger">下架</button>'
                        }
                    }
                    , {field: 'price', title: '售价', align: 'center', width: 80}
                    , {field: 'remark', title: '备注', align: 'center'}
                    , {fixed: 'right', title: '操作', toolbar: '#userBar', align: 'center'}
                ]]
                , limit: 8
                , limits: [3, 5, 8, 10, 20, 50]
            });
        }

        //监听头部工具栏
        table.on("toolbar(bookTable)", function (obj) {
            switch (obj.event) {
                case 'addBook':
                    openAddBookDiv();
                    break;
                case 'refresh':
                    showTable();
                    break;
            }
        });

        //监听右侧工具栏
        table.on('tool(bookTable)', function (obj) { //注：tool 是工具条事件名，userTable 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            if (obj.event === 'modify') {
                showModifyBookDiv(data)
            } else if (obj.event === 'delete') {
                showDeleteBookDiv(data);
            }
        });

        //页面加载完成，调用的方法
        $(function () {
            //页面加载完成,初始化员工表
            showTable();
        });

        // 商品上下架后台提交
        function showDeleteBookDiv(data) {
            layer.confirm('确定上/下架吗', function (index) {
                $.ajax({
                    url: '/bookServlet/updateStatus',
                    type: 'post',
                    data: {bookid: data.bookid, status: data.status},
                    dataType: 'json',
                    success: function (result) {
                        console.log(result)
                        if (Number(result) > 0) {
                            showTable()
                            toastr.success("操作成功")
                        } else {
                            toastr.error("操作失败")
                        }
                    }
                })
                layer.close(index);
            });
        }

        //打开添加图书的弹出层
        function openAddBookDiv() {
            $("#addForm")[0].reset();
            layer.open({
                type: 1,
                anim: 3,
                title: ['添加图书', 'font-size:20px'],
                content: $("#addBookDiv"),
                offset: '50px',
                area: '400px',
            })
        }
        // 打开修改图书的弹出层
        function showModifyBookDiv(data) {
            $("#addForm")[0].reset();
            layer.open({
                type: 1,
                anim: 3,
                title: ['修改图书', 'font-size:20px'],
                content: $("#addBookDiv"),
                offset: '50px',
                area: '400px',
                success:function () {
                    form.val('addForm',data);
                    form.render('select');
                }
            })
        }

        // 添加、修改数据表格表单验证
        form.verify({
            price: [
                /^[1-9]\d*\.?\d*|0\.\d*$/
                , '价格只能是大于0的整数或者小数'
            ]
        });

        // 添加、修改的表单提交
        form.on('submit(addBtn)', function (data) {
            $.ajax({
                url: 'bookServlet/addBook',
                type: 'post',
                dataType: 'json',
                data: data.field,
                async: false,
                success: function (result) {
                    let resultValue = Number(result);
                    if (resultValue === 0) {
                        toastr.error("该书已经存在，请勿重新添加");
                    } else if (resultValue === 1) {
                        toastr.success("操作成功")
                        showTable();
                        layer.closeAll();
                    } else {
                        toastr.error("操作失败")
                        layer.closeAll();
                    }
                }
            })
        })

    })
</script>
</body>
<style>
    .layui-table th {
        font-weight: bold;
    }

    .layui-table-cell {
        height: 36px;
        line-height: 36px;
    }

    /*下拉框高度*/
    .layui-unselect dl {
        max-height: 200px;
    }

</style>
</html>
